// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::path::PathBuf;

use futures_util::StreamExt;
use maestro_derive::MsgTag;
use ohmw_derive::{Decode, Encode};

use crate::system::ros::{find_msg_files, get_package_paths};

#[derive(Encode, Decode, MsgTag)]
#[msg_tag(case = "snake_case")]
pub struct CollectMessagesRet {
    pub path: String,
    pub messages: Vec<String>,
}

pub async fn collect_messages(path: &str) -> CollectMessagesRet {
    let mut messages = vec![];
    let packages = get_package_paths(vec![PathBuf::from_iter([path])]);
    for package in packages {
        let msg_dir = package.path.join("msg");
        let Ok(mut find_msg_files) = find_msg_files(&msg_dir).await else {
            continue;
        };
        while let Some(path) = find_msg_files.next().await {
            let Ok(path) = path else {
                continue;
            };
            let Some(file_stem) = path.file_stem() else {
                continue;
            };
            messages.push(format!("{}/{}", package.name, file_stem.to_string_lossy()));
        }
    }

    CollectMessagesRet {
        path: path.to_string(),
        messages,
    }
}